import axios from 'axios';
import { ElMessage, ElLoading } from 'element-plus';
import router from '../router';

const TOKEN_INVALID: any = 'TOKEN过期请重新登录';
const NETWORK_ERROR: any = '网络请求异常,请稍后再试';
// 创建axios实例对象，添加全局配置
axios.defaults.withCredentials = true;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
const service = axios.create({
  baseURL: 'http://c.fanglingdi.com',
  timeout: 80000,
});
// 请求拦截
service.interceptors.request.use((req) => req);
// 响应拦截
service.interceptors.response.use((res) => {
  const { errCode, data, errMsg } = res.data;
  if (errCode == 200) {
    return data;
  } if (errCode == 40001) {
    ElMessage.error(TOKEN_INVALID);
    setTimeout(() => {
      router.push('/login');
    }, 15000);
    return Promise.reject(TOKEN_INVALID);
  }
  ElMessage.error(errMsg || NETWORK_ERROR);
  return Promise.reject(errMsg || NETWORK_ERROR);
});

function request(options: { method: string; params: any; data: any }):any {
  options.method = options.method || 'get';
  // get 请求
  if (options.method.toLowerCase() === 'get') {
    options.params = options.data;
  }
  return service(options);
}

['get', 'post', 'put', 'delete', 'patch'].forEach((item:any) => {
  request[item] = (url: any, data: any, options: { method: string; params: any; data: any }) => request({
    url,
    data,
    method: item,
    ...options,
  });
});

export default request;